package org.blackcat.dao.redis;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

/**
 * Created by Duo Duo on 2017/1/4.
 */
@Component
public class RedisPools {

    @Value("${redis.ip}")
    private String ip;
    @Value("${redis.auth}")
    private String auth;
    @Value("${redis.port}")
    private int port;
    @Value("${redis.maxActive}")
    private int maxActive;
    @Value("${redis.maxIdle}")
    private int maxIdle;
    @Value("${redis.maxWaitMillis}")
    private int maxWaitMillis;
    @Value("${redis.timeout}")
    private int timeout;
    @Value("${redis.testOnBorrow}")
    private boolean testOnBorrow;

    private static JedisPool jedisPool = null;

    public void init(){
        if(jedisPool == null){
            JedisPoolConfig config = new JedisPoolConfig();
            config.setMaxActive(maxActive);
            config.setMaxIdle(maxIdle);
            config.setMaxWait(maxWaitMillis);
            config.setTestOnBorrow(testOnBorrow);
            jedisPool = new JedisPool(config,ip,port,timeout,auth);
        }
    }

    /**
     * 获取jedis实例
     */
    public Jedis getJedisResource(){
        init();
        Jedis jedis = jedisPool.getResource();
        return jedis;
    }

    /**
     * 释放jedis资源
     */
    public void returnJedisResource(final Jedis jedis){
        if(jedis != null){
            jedisPool.returnResource(jedis);
        }
    }

    public void setIp(String ip) {
        this.ip = ip;
    }

    public void setAuth(String auth) {
        this.auth = auth;
    }

    public void setPort(int port) {
        this.port = port;
    }

    public void setMaxActive(int maxActive) {
        this.maxActive = maxActive;
    }

    public void setMaxIdle(int maxIdle) {
        this.maxIdle = maxIdle;
    }

    public void setMaxWaitMillis(int maxWaitMillis) {
        this.maxWaitMillis = maxWaitMillis;
    }

    public void setTimeout(int timeout) {
        this.timeout = timeout;
    }

    public void setTestOnBorrow(boolean testOnBorrow) {
        this.testOnBorrow = testOnBorrow;
    }
}
